package com.ls.lserp.modules.setting.web;

import com.ls.lserp.modules.sys.utils.SystemMessageUtils;
import groovy.util.ResourceException;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
	import javax.servlet.http.HttpServletResponse;
	import javax.servlet.http.HttpSession;
	import org.apache.shiro.authz.annotation.RequiresPermissions;
	import org.springframework.beans.factory.annotation.Autowired;
	import org.springframework.stereotype.Controller;
	import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.drew.lang.StringUtil;
import com.ls.lserp.common.config.Global;
import com.ls.lserp.common.persistence.AjaxDone;
import com.ls.lserp.common.persistence.BaseEntity;
import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.utils.FileUtils;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.StringUtils;
import com.ls.lserp.common.utils.SystemPath;
import com.ls.lserp.common.web.BaseController;
import com.ls.lserp.modules.common.entity.Material;
import com.ls.lserp.modules.common.entity.UploadFile;
import com.ls.lserp.modules.setting.entity.CompanyList;
import com.ls.lserp.modules.setting.entity.CompanyUser;
import com.ls.lserp.modules.setting.entity.Ognization;
import com.ls.lserp.modules.setting.service.CompanyUserService;
import com.ls.lserp.modules.sys.entity.Dict;
import com.ls.lserp.modules.sys.entity.User;
import com.ls.lserp.modules.sys.service.SystemService;
import com.ls.lserp.modules.sys.utils.DictUtils;
import com.ls.lserp.modules.sys.utils.UserUtils;

	@Controller
	@RequestMapping(value = "${adminPath}/companyuser/message")
	public class CompanyUserController extends BaseController{
		@Autowired
	    private CompanyUserService companyUserService;
		
		// 子项session
		private final String COMPANYUSERLIST= "companyUserList";
		
		/**
		 * 进入一览页面
		 * @param id
		 * @return
		 */
		@ModelAttribute
		public CompanyUser get(@RequestParam(required=false) String id) {
			
			// 判断id是否为空
			if (StringUtils.isNotBlank(id)){
				
				// 执行查询语句 查询基本信息
				return companyUserService.get(Long.parseLong(id));
			}else{
				
				// 若为空，实例化
				return new CompanyUser();
			}
			
		}

		/**
		 * @Title: 画面跳转用
		 * @param companyUser
		 * @param request 
		 * @param response 
		 * @param model 
		 *  @return url
		 */
		@RequiresPermissions("companyuser:message:view")
		@RequestMapping(value = { "" })
		public String list(CompanyUser companyUser, HttpServletRequest request, HttpServletResponse response, Model model) {
			// 获取人员组表信息
			CompanyUser companyUserTemp = companyUserService.getDutyList(companyUser);
			//  获取职务表信息
			CompanyUser companyGroupTemp = companyUserService.getUserGroupList(companyUser);
			// 获取角色信息表
			CompanyUser companyRoleTemp = companyUserService.getRoleList(companyUser);
			// 前台select组件使用（人员组表）
			model.addAttribute("companyUserTemp", companyUserTemp);
			// 前台select组件使用（职务表）
			model.addAttribute("companyGroupTemp", companyGroupTemp);
			// 前台select组件使用（角色信息表）
			model.addAttribute("companyRoleTemp", companyRoleTemp);
			// 画面跳转
			return "modules/setting/companyUser";
		}


		/**
		 * @Title: 画面检索
		 * @Description: 查询页面 
		 * @param companyUser
		 * @param request 
		 * @param response 
		 * @param model 
		 * @return searchList
		 * @throws ResourceException
		 */
		@RequiresPermissions("companyuser:message:view")
		@RequestMapping(value = { "searchList" })
		@ResponseBody
		public String searchList(CompanyUser companyUser, HttpServletRequest request, HttpServletResponse response, Model model)
				throws ResourceException {
			Map<Object, Object> listMap = new HashMap<Object, Object>();
			FileUtils filUtils = new FileUtils();
			DateFormat dateForamat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			// ajax回调时使用的一览list名
			request.setAttribute(Global.LIST_NAME, "companyUser");
			// 画面取得的检索项目 公司
			String ognizationName = companyUser.getOgnizationName();
			// 画面取得的检索项目 职务
			String searchDutyId = companyUser.getSearchDutyId();
			String searchRoleId = companyUser.getSearchRoleId();
			String searchGroupId = companyUser.getSearchGroupId();
			if (StringUtils.isNotEmpty(searchDutyId)){
				companyUser.setDutyId(Long.parseLong(searchDutyId));
			}
			if (StringUtils.isNotEmpty(searchRoleId)){
				companyUser.setRoleId(Long.parseLong(searchRoleId));
			}
			if (StringUtils.isNotEmpty(searchGroupId)){
				companyUser.setGroupId(Long.parseLong(searchGroupId));
			}
			// 画面取得的检索项目 员工名
			String comUserName = companyUser.getComUserName();
			// 画面取得的检索项目 手机号码
			String mobile = companyUser.getMobile();
			// 拼接字符串供分页使用
			String searchParam = "&ognizationName="+ognizationName+"&searchDutyId="+searchDutyId+"&searchRoleId="+searchRoleId+"&searchGroupId="+searchGroupId+"&comUserName="+comUserName+"&mobile="+mobile;
			// 放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
			request.setAttribute(Global.SEARCH_PAEAM, searchParam);
			// 查询一览页面数据
			Page<CompanyUser> page = companyUserService.findList(new Page<CompanyUser>(request, response), companyUser);
			// 读取系统路径
			String basePath = SystemPath.getClassPath();
			String tempFilePath = "//"+basePath + "templates//demoHtml//companyUser.txt";
			// 读取文件生成字符串
			String companyUserHtml = filUtils.readFileToHtml(tempFilePath);
			String strHtml = "";
			String creator = "";
			String userfirstNameEn = "";
			String userlastNameEn = "";
			int pageNo = 0;
			String strUri = request.getContextPath()+Global.getAdminPath();
			if (!"".equals(companyUserHtml)) {
				for (int i = 0; i < page.getList().size(); i++) {
					companyUserHtml = filUtils.readFileToHtml(tempFilePath);
					// 画面No
					pageNo = (page.getPageNo() - 1) * page.getPageSize() + (i + 1);
					companyUserHtml = companyUserHtml.replace("pageNo", "" + pageNo);
					// 员工姓名
					/*companyUserHtml = companyUserHtml.replace("firstNameEn", StringUtils.checkStringNull(page.getList().get(i).getFirstNameEn()));
					String companyUserline = "\"popup('900px','584px','"+strUri+"/companyuser/message/show?id=" 
							+ page.getList().get(i).getId() + "')\"";*/
		
					companyUserHtml=companyUserHtml.replace("comUserName", StringUtils.checkStringNull(page.getList().get(i).getComUserName()));
					String companyUserline = "\"popup('900px','584px','"+strUri+"/companyuser/message/show?id=" 
							+ page.getList().get(i).getId() + "&editFlag=1')\"";
					// 员工号
					companyUserHtml = companyUserHtml.replace("userNo", StringUtils.checkStringNull(page.getList().get(i).getUserBarcode()));
					// 员工姓名popup
					companyUserHtml = companyUserHtml.replace("firstnamepopup", companyUserline);
					// 性别
//					companyUserHtml = companyUserHtml.replace("sex", StringUtils.checkStringNull(page.getList().get(i).getSex()));
					companyUserHtml = companyUserHtml.replace("sex", StringUtils.checkStringNull(DictUtils.getDictName(page.getList().get(i).getSex())));
					// 身份证号
					companyUserHtml = companyUserHtml.replace("idientityCardNumber", StringUtils.checkStringNull(page.getList().get(i).getIdientityCardNumber()));
					// Email
					companyUserHtml = companyUserHtml.replace("stremail", StringUtils.checkStringNull(page.getList().get(i).getEmail()));
					// 联系电话
					companyUserHtml = companyUserHtml.replace("mobile", StringUtils.checkStringNull(page.getList().get(i).getMobile()));
					// 员工地址
					companyUserHtml = companyUserHtml.replace("address", StringUtils.checkStringNull(page.getList().get(i).getAddress()));
					// 员工角色
					companyUserHtml = companyUserHtml.replace("roleName", StringUtils.checkStringNull(page.getList().get(i).getRoleName()));
					// 员工职务
					companyUserHtml = companyUserHtml.replace("dutyName", StringUtils.checkStringNull(page.getList().get(i).getDutyName()));
					// 员工组别
					companyUserHtml = companyUserHtml.replace("groupName", StringUtils.checkStringNull(page.getList().get(i).getGroupName()));
					
					// 创建者
					User createUser = UserUtils.get(page.getList().get(i).getCreateBy().getId());
					creator = createUser.getFirstName()
							+ createUser.getLastName();
					companyUserHtml = companyUserHtml.replace("createUser", StringUtils.checkStringNull(creator));
//					createUser = page.getList().get(i).getCreateBy().getFirstName()
//							+ page.getList().get(i).getCreateBy().getLastName();
//					companyUserHtml = companyUserHtml.replace("createUser", createUser);
					// 创建日期
					dateForamat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
					Date createDate = page.getList().get(i).getCreateDate();
					if (createDate!=null) {
						companyUserHtml = companyUserHtml.replace("createDate", dateForamat.format(createDate));
					}else {
						companyUserHtml = companyUserHtml.replace("createDate", "");
					}
					strHtml += companyUserHtml;
				}
			}
			listMap.put("companyUser", strHtml);
			listMap.put("page", page.getHtml());
			
			// ajax返回结果
			return renderString(response, listMap);
		}
		
		/**
		 * 
		 * 功能：Java读取txt文件的内容 1：先获得文件句柄 2：获得文件句柄当做是输入一个字节码流，需要对这个输入流进行读取
		 * 3：读取到输入流后，需要读取生成字节流
		 * 
		 * @param filePath
		 * @return html
		 */
		public String readTxtFile(String filePath) {
			String strHtml = "";
			try {
				String encoding = "UTF-8";
				File file = new File(filePath);
				// 判断文件是否存在
				if (file.isFile()) {
					InputStreamReader read = new InputStreamReader(
							// 考虑到编码格式
							new FileInputStream(file), encoding);
					BufferedReader bufferedReader = new BufferedReader(read);
					String lingText = null;
					while ((lingText = bufferedReader.readLine()) != null) {
						strHtml += lingText;
					}
					read.close();
				} else {

				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return strHtml;
		}
		
		
		/**
	     * 进入查看页面
	     * @param companyUser
	     * @param model
	     * @return
	     */
	    @RequiresPermissions("companyuser:message:view")
	    @RequestMapping(value = "show")
	    public String show(CompanyUser companyUser, Model model) {
	 
	        // 将查询结果赋值mvc model层返回jsp页面
	        model.addAttribute("companyUser", companyUser);
	        
	        // 返回页面地址
	        return "modules/setting/companyUserShow";
	    }
		
		
		/**
	     * @Title: 新建
		 * @Description: 新建
		 * @param CompanyUser
		 * @param redirectAttributes
		 * @param model
		 * @param session
	     * @return form
		 */
		@RequiresPermissions("companyuser:message:edit")
		@RequestMapping(value = "form")
		public String form(CompanyUser companyUser, RedirectAttributes redirectAttributes, Model model, HttpSession session) {
				// 获取人员组表信息
				CompanyUser companyUserTemp = companyUserService.getDutyList(companyUser);
				//  获取职务表信息
				CompanyUser companyGroupTemp = companyUserService.getUserGroupList(companyUser);
				// 获取角色信息表
				CompanyUser companyRoleTemp = companyUserService.getRoleList(companyUser);
				// 获取组织集团表
				CompanyUser companyOgnizationTemp = companyUserService.getOgnizationList(companyUser);
				// 前台select组件使用（人员组表）
				model.addAttribute("companyUserTemp", companyUserTemp);
				// 前台select组件使用（职务表）
				model.addAttribute("companyGroupTemp", companyGroupTemp);
				// 前台select组件使用（角色信息表）
				model.addAttribute("companyRoleTemp", companyRoleTemp);
				// 前台select组件使用（组织集团表）
				model.addAttribute("companyOgnizationTemp", companyOgnizationTemp);
				
				// 性别
				List<Dict> sexList = DictUtils.getDictList(ResourcesUtil.getConfig("sex"));
				model.addAttribute("sexList", sexList);
				
				/*if(companyUser.getId()==null){
					companyUser.preInsert();
				}*/
				
				// 将实体类值赋给mvc model层返回jsp页面
				model.addAttribute("companyUser", companyUser);
			
				// 返回页面地址
				return "modules/setting/createCompanyUser";
			}
		
		
		/**
		 * 保存信息
		 * @param companyUser
		 * @param request
		 * @param model
		 * @param response
		 * @return
		 * @throws ResourceException 
		 */
		@RequiresPermissions("companyuser:message:edit")
		@RequestMapping(value = "save")
		@ResponseBody
		public String save(CompanyUser companyUser, HttpServletRequest request, Model model, HttpServletResponse response , HttpSession session) throws ResourceException {
			
		// 判断id是否为null （判断新建或修改）
			if(companyUser.getId()!=null){
				
				// 判断数据是否删除
				CompanyUser companyUserNew = get(companyUser.getId().toString());
				// 判断数据是否删除
	            if(companyUserNew==null || BaseEntity.DEL_FLAG_DELETE.equals(companyUserNew.getDeleteFlag())){
	            	// 返回提示信息
	            	return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
	            }
	            /*		
	            // 排他处理
			    if((companyUser.getVersion()==get(companyUser.getId().toString()).getVersion()))
			    {
			    	// 版本号加1
			    	companyUser.setVersion(companyUser.getVersion()+1);
			    	
			    }else{
			    	
			    	// 返回提示信息
			        return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
			    }
				*/
			}

			    // 密码加密
			    String newPassword = SystemService.entryptPassword(companyUser.getPassword());
			    companyUser.setPassword(newPassword);
			
		        // 保存数据
   		        companyUserService.saveCompanyUser(companyUser);
				
				// 保存成功返回提示信息
		        return renderString(response,AjaxDone.ok(SystemMessageUtils.getMessageName( "customer_save_success")));
		}

		/**
		  * @Title: sysLoginForgetPassword04
		  * @Description: 保存密码
		*/
/*		@RequestMapping(value = "${adminPath}/forgetPassword/sysLoginForgetPassword04")
		public String sysLoginForgetPassword04(CompanyUser companyUser,String oldPassword, RedirectAttributes redirectAttributes,Model model, HttpServletResponse response){
			CompanyUser newPassword =companyUserService.getByLoginName(companyUser.getLoginName());
	        	newPassword.setPassword(SystemService.entryptPassword(companyUser.getPassword()));
	    		// 保存密码
	        	companyUserService.updatePassword(newPassword);
	    		model.addAttribute("companyUser", companyUser);
			// 提示保存成功信息
			return "modules/sys/sysLoginForgetPassword04";
		}*/
		
		
		/**
		 * 删除信息
		 * @param companyUser
		 * @param companyUser
		 * @param response
		 * @return
		 */
	    @RequiresPermissions("companyuser:message:edit")
		@RequestMapping(value = "delete")
		public String delete(CompanyUser companyUser, HttpServletResponse response) {
			
			    try {
			    	
			    	// 执行逻辑删除方法
			    	companyUserService.deleteCompanyUser(companyUser);
	            } catch (Exception e) {
	                // 记录日志
	                logger.error(e.getMessage(), e);
	            	// 提示错误信息
	                return renderString(response,AjaxDone.error(getText("System_error_please_contact_your_administrator")));
	            }
			    
			    // 提示删除成功信息
				return renderString(response,AjaxDone.ok(getText("dict_delete_success")));
	    }

	    
	}
